
var express = require('express');
var router = express.Router();
var { qfuser_model } = require("../utils/model")
var { createToken, checkToken } = require("../utils/token")
var qs = require("qs")
var axios = require("axios")
var multer = require("multer")




// Vue3.0  项目的接口 
router.get("/test", (req, res) => {
  res.send("API - API  - TEST ")
})

router.get("/index", (req, res) => {
  res.json({
    code: 200,  // 200 成功
    msg: "测试成功",
    result: null
  })
})

//注册
router.post("/register", (req, res) => {
  var body = req.body;
  qfuser_model.findOne({
    $or: [
      {
        username: body.username
      },
      {
        phone: body.phone
      }
    ]
  })
    .then(data => {
      if (data) {
        res.json({
          code: 3001,
          msg: "当前用户已经注册",
          result: data
        })
      } else {
        // 直接插入
        body.time = new Date()
        qfuser_model.insertMany(body)
          .then(result => {
            res.json({
              code: 200,
              msg: "注册成功",
              result
            })
          })
      }
    })
    .catch(err => {
      res.json({
        code: 500,
        msg: "服务器异常",
        err
      })
    })
})


//登录
router.post("/loginusername", (req, res) => {
  var body = req.body;
  qfuser_model.findOne({
    username: body.username
  })
    .then(data => {
      if (data) {

        if (data.password == body.password) {
          // 生成 token  
          const token = createToken(body)
          res.json({
            code: 200,
            msg: "登录成功",
            result: data,
            token
          })
        } else {
          res.json({
            code: 401,
            msg: "用户名和密码不匹配,登录失败",

          })
        }
      } else {


        res.json({
          code: 3001,
          msg: "用户名不存在，登录失败",
          err
        })

      }
    })
    .catch(err => {
      res.json({
        code: 500,
        msg: "服务器异常",
        err
      })
    })
})

// 获取用户信息
router.post("/getuserinfo", (req, res) => {
  checkToken(req, res, ({ username }) => {
    qfuser_model.findOne({
      username
    })
      .then(result => {
        res.json({
          code: 200,
          msg: "获取个人信息成功",
          result
        })
      })
      .catch(err => {
        res.json({
          code: 500,
          msg: "服务器异常",
          err
        })
      })
  })
})

// 发送验证码
router.post("/sendcaptcha", (req, res) => {
  var body = req.body;
  qfuser_model.findOne({
    phone: body.phone
  })
    .then(result => {
      if (result) {
        // 发送码 
        axios.get("http://47.104.209.44:3333/captcha/sent", {
          params: {
            phone: body.phone
          }
        })
          .then(result => {
            console.log(result)
            if (result.data.code == 200) {
              res.json({
                code: 200,
                result: result.data,
                msg: "发送成功"
              })
            } else {
              res.json({
                code: 401,
                result: result.data,
                msg: "发送失败"
              })
            }

          })
      } else {
        res.json({
          code: 401,
          msg: "当前手机号还未注册,无法发送验证码"
        })
      }
    })
    .catch(err => {

      res.json({
        code: 500,
        msg: "服务器异常",
        err
      })
    })
})


// 校验验证码

router.post("/verifycaptcha", (req, res) => {
  var body = req.body;
  qfuser_model.findOne({
    phone: body.phone
  })
    .then(value => {
      if (value) {
        // 发送码 
        axios.get("http://47.104.209.44:3333/captcha/verify", {
          params: body
        })
          .then(result => {
            console.log(result)
            if (result.data.code == 200) {
              // token
              var token = createToken({
                phone: value.phone,
                username: value.username
              })
              res.json({
                code: 200,
                result: result.data,
                msg: "登录成功",
                token
              })
            } else {
              res.json({
                code: 401,
                result: result.data,
                msg: "登录失败"
              })
            }

          })
      } else {
        res.json({
          code: 401,
          msg: "当前手机号还未注册,请先注册"
        })
      }
    })
    .catch(err => {
      console.log(err);
      res.json({
        code: 500,
        msg: "服务器异常",
        err
      })
    })
})



// 上传头像
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, './public/images/uploads')
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)

    cb(null, "WH2110_" + new Date().getTime() + "_" + file.originalname) // photo.png => wh2110photo.122312124123.png  文件名冲突  
  }
})

const upload = multer({ storage: storage }).any()

// 上传文件
router.post("/uploadfile", upload, (req, res) => {
  checkToken(req, res, ({ username }) => {
    console.log(req.files)
    var file = req.files[0]
    res.json({
      code: 200,
      msg: "上传成功",
      path: file.path,  // 上传成功的相对于服务器的路径  
      result: file.path
    })
  })
})
// 修改个人信息
router.post("/changeinfo", (req, res) => {
  var body = req.body
  checkToken(req, res, ({ username }) => {
    qfuser_model.updateMany({
      username
    }, {
      $set: {
        avatar: body.avatar
      }
    })
      .then(result => {
        res.json({
          code: 200,
          msg: "修改成功",
          result: result
        })
      })
      .catch(err => {
        res.json({
          code: 500,
          msg: "服务器异常",
          err
        })
      })
  })
})


// 修改密码
router.post("/changepass", (req, res) => {
  var body = req.body
  checkToken(req, res, ({ username }) => {
    qfuser_model.findOne({
      username
    })
      .then(result => {
        if (result.password == body.oldpass) {
          // 修改
          qfuser_model.updateMany({
            username
          }, {
            $set: {
              password: body.newpass
            }
          })
            .then(result => {
              res.json({
                code: 200,
                msg: "密码修改成功，请重新登录",
                result
              })
            })
        } else {
          res.json({
            code: 401,
            msg: "原始密码错误",
          })
        }
      })
      .catch(err => {
        res.json({
          code: 500,
          msg: "服务器异常",
          err
        })
      })
  })
})

module.exports = router;
